package com.ayf.payment.game.api.utils;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.type.CharSetEnum;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class MyGDIPCityUtil {

    private static final String url = "https://restapi.amap.com/v3/ip?output=json&key=";

    public static String getCityNameByIp(String reqIp){
        BaseResData baseResData =  sendGet(SnowFlakeUtils.getTraceId(),"根据IP获取城市名称",reqIp);
        if (baseResData.isSuccess()){
           JSONObject dataJson= JSONObject.parseObject(baseResData.getData());
           if ("1".equals(dataJson.getString("status"))){ // 值为0或1,0表示失败；1表示成功
               return dataJson.getString("city");
           } else {
               return "未知";
           }
        } else {
            return "未知";
        }
    }

    private static BaseResData sendGet(String traceId,String methodDesc,String reqIp) {
        //声明返回结果
        String result = "";
        //开始请求API接口时间
        long startTime=System.currentTimeMillis();
        //请求API接口的响应时间
        long endTime= 0L;
        int responseCode=-1;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        HttpEntity httpEntity = null;
        BaseResData baseResData = new BaseResData();
        try {
            org.apache.http.client.config.RequestConfig requestConfig = org.apache.http.client.config.RequestConfig.custom().
                    setConnectTimeout(10 * 1000).
                    setConnectionRequestTimeout(10 * 1000).
                    setSocketTimeout(30 * 1000). //超时最大等待时间
                    build();

            String myurl = url.concat(StringUtils.defaultIfEmpty(System.getenv("XY_GD_SECRET_KEY"),"--")).concat("&ip=").concat(reqIp);
            // 创建连接
            if (myurl.startsWith("https")){
                httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setSSLSocketFactory(new SSLConnectionSocketFactory(getSslContext())).build();
            } else {
                httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
            }
            Charset charset = Charset.forName(CharSetUtil.getCharSet(CharSetEnum.utf8));
            HttpGet httpPost = new HttpGet(myurl);
            LogPortal.info("{} {}请求开始 URL:{}",traceId,methodDesc,myurl);
            response = httpClient.execute(httpPost);
            responseCode = response.getStatusLine().getStatusCode();
            if (responseCode ==200){
                httpEntity = response.getEntity();
                if (httpEntity != null) {
                    result = EntityUtils.toString(httpEntity,charset);
                    baseResData.setData(result);
                }
                if (StringUtils.isEmpty(result)){
                    baseResData.setRespMsg("响应报文内容为空");
                } else {
                    baseResData.setSuccess(true);
                }
            } else {
                baseResData.setRespMsg("HttpStatus非200，当前是:"+responseCode);
                httpEntity = response.getEntity();
                if (httpEntity != null) {
                    result = EntityUtils.toString(httpEntity,charset);
                    baseResData.setData(result);
                }
            }
        } catch (ConnectTimeoutException e) {
            baseResData.setRespMsg(e.getClass().getName().concat(" 异常描述:".concat(e.getMessage())));
        } catch (SocketTimeoutException e) {
            baseResData.setProcessing(true);
            baseResData.setRespMsg(e.getClass().getName().concat(" 异常描述:".concat(e.getMessage())));
        }catch (SocketException e) {
            baseResData.setRespMsg(e.getClass().getName().concat(" 异常描述:".concat(e.getMessage())));
        } catch (Exception e) {
            baseResData.setRespMsg("发生"+e.getClass().getName()+"异常，错误码:"+traceId);
            LogPortal.error("{} {}http请求发生{}异常",e,traceId,methodDesc,e.getClass().getName());
        } finally {
            try {
                if (httpEntity != null){
                    EntityUtils.consume(httpEntity);
                }
            } catch (IOException e) {
                LogPortal.error("{} {}http请求释放资源异常",e,traceId,methodDesc);
            }
        }
        //请求接口的响应时间
        endTime=System.currentTimeMillis();
        LogPortal.info("{} {}耗时:{}ms httpStatus:{} 响应报文:{}",traceId,methodDesc,(endTime-startTime),responseCode,result);
        return baseResData;
    }

    private static SSLContext getSslContext() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }}, new SecureRandom());
        return sslContext;
    }

    public static void main(String[] args) {
        System.out.println(MyGDIPCityUtil.getCityNameByIp("183.242.85.10"));
    }
}
